<!--
 * @Author: 大国男儿 7824741+lc2677@user.noreply.gitee.com
 * @Date: 2022-12-01 16:15:05
 * @LastEditors: 大国男儿 7824741+lc2677@user.noreply.gitee.com
 * @LastEditTime: 2022-12-05 10:03:45
 * @FilePath: \vue-openlayers\src\views\function\function4.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->

<template>
  <div class="container">
    <h3>vue+openlayers: 添加地图地点搜索定位功能</h3>
    <div id="vue-openlayers"/>
  </div>
</template>
<script>
import 'ol/ol.css'
import Map from 'ol/Map'
import View from 'ol/View'
import LayerTile from 'ol/layer/Tile'
import { XYZ } from 'ol/source'
import 'ol-popup/src/ol-popup.css'
import Popup from 'ol-popup'
import 'ol-geocoder/dist/ol-geocoder.css'
import Geocoder from 'ol-geocoder'

export default {
  name: 'Mapbox',
  data() {
    return {
      map: null
    }
  },
  mounted() {
    this.initMap()
  },
  methods: {
    initMap() {
      this.map = new Map({
        layers: [
          new LayerTile({
            title: 'OSM',
            type: 'base',
            visible: true,
            source: new XYZ({
              url: 'http://{a-c}.tile.openstreetmap.de/{z}/{x}/{y}.png'
            })
          })
        ],
        target: 'vue-openlayers',
        view: new View({
          center: [13247019.404399557, 4721671.572580107],
          projection: 'EPSG:3857',
          zoom: 4
        })
      })

      const popup = new Popup()
      const geocoder = new Geocoder('nominatim', {
        provider: 'photon',
        targetType: 'glass-button',
        lang: 'en',
        placeholder: 'Search for ...',
        limit: 5,
        keepOpen: false
      })

      this.map.addControl(geocoder)
      this.map.addOverlay(popup)
      // Listen when an address is chosen
      geocoder.on('addresschosen', (evt) => {
        window.setTimeout(() => {
          popup.show(evt.coordinate, evt.address.formatted)
        }, 3000)
      })
    }
  }

}
</script>

<style scoped>
.container {
  width: 840px;
  height: 520px;
  margin: 50px auto;
  border: 1px solid #42b983;
}

#vue-openlayers {
  width: 800px;
  height: 400px;
  margin: 0 auto;
  border: 1px solid #42b983;
  position: relative;
}
</style>

